﻿using System;
using System.Net;
using Newtonsoft.Json;

namespace YourAppNamespaceHere // Replace with your own namespace
{
    public class Json
    {

        /// Root is the access point for
        /// the actual cafeterian menu information.
        public menuRoot m_root;

        /// <summary>
        /// Initialize Json object, sets the m_root item to null
        /// </summary>
        public Json() { m_root = null; }


        /// <summary>
        /// Deserializes a json format string into Juvenes
        /// type object 'menuRoot'.
        /// </summary>
        /// <param name="json">Json format string, for more information about
        /// the format check json.net</param>
        public void DeserializeToJuvenes(string json)
        {
            m_root = JsonConvert.DeserializeObject<menuRoot>(json);
        }

        // Creates the menu items
        public void CreateMenu(menuRoot jsonObject)
        {
            // Other ingredients is string used to construct
            // the ingredients after main ingredient for example
            // "Creame Sauce, dark rice" or what ever suppliments
            // There is
            string otherIngredients = "";
            
            // If the jsonObject given in the parameters is not null go through
            // all the different meals and create display items from them.
            if (jsonObject != null)
            {
                for (int i = 0; i < jsonObject.Meals.Count; i++)
                {
                    for (int j = 1; j < jsonObject.Meals[i].menuItems.Count; j++)
                    {
                        otherIngredients += jsonObject.Meals[i].menuItems[j].name;
                    }
                    // Here you want to push the items to your display pipeline if you use 
                    // LongListSelector then use Add command if something else then adjust accordingly.
                    // MealHead and MealBody have to be binded to your XAML you can check from my app
                    // how I did it once its uploaded. 
                    Items.Add(new ViewModels.ItemViewModel() 
                        { MealHead = jsonObject.Meals[i].menuItems[0].name, MealBody = otherIngredients });
                    
                    // Empty the otherIngredients string for the next meal.
                    otherIngredients = "";
                }
            }

        }
        /// <summary>
        /// Asynchroniously fetches the Json data as a string from Juvenes webservice according to parameters.
        /// for more information about parameters check Juvenes.txt in my repository at projects.developer.nokia.com/treruokalat/
        /// once the download from webservice is complete DownloadStringCompleteEvent is fired and webClient_DownloadStringComplited is
        /// called
        /// </summary>
        /// <param name="kitchen">check Juvenes.txt for information about these values</param>
        /// <param name="menuType">check Juvenes.txt for information about these values</param>
        /// <param name="week">weeks from 1 through 52</param>
        /// <param name="day">weekdays monday being 1</param>
        /// <param name="language">Either 'fi' or 'en'</param>
        public void GetJsonData(int kitchen, int menuType, int week, int day, string language)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringComplited);

            webClient.DownloadStringAsync(new System.Uri("http://www.juvenes.fi/DesktopModules/Talents.LunchMenu/LunchMenuServices.asmx/GetMenuByWeekday?KitchenId="+kitchen+"&MenuTypeId="+menuType+"&Week="+week+"&Weekday="+day+"&lang="+language+"&format=json"));
        }

        /// <summary>
        /// Formats the Json string so that its readable by JSON.Net Deserializer
        /// more information about the problems in the JSON data can be found in
        /// Juvenes.txt
        /// </summary>
        /// <param name="json">String to be cleaned</param>
        /// <returns></returns>
        public String CleanJson(String json)
        {
            int index = json.IndexOf("\"});");
            int indexStart = json.IndexOf("{", 4);
            int length = index - indexStart;
            string substr = json.Substring(indexStart, length);
            substr = substr.Replace("\\\"", "\"");
            return substr;
        }
 
        /// <summary>
        /// Event handling that will be fired once the json is downloaded from webserver.
        /// </summary>
        /// <param name="Sender">Who called the eventhandler</param>
        /// <param name="args">Arguments for the event including the read string</param>
        private void webClient_DownloadStringComplited(object Sender, DownloadStringCompletedEventArgs args)
        {
            // If there were errors during the downloading then show popup messagebox.
            if (args.Error != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Error, Could not connect to server!");
                });
            }
            // Else cleanup the string and deserialize and after that
            // create the XAML items for the app.
            else
            {

                string str = CleanJson(args.Result);
                m_root = Deserialize(str);
                CreateMenu(m_root);
            }
        }
    }


}
